package com.jnu.textbook;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.model.LatLng;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MapFragment extends Fragment {

    public static final int WHAT_DATA_OK = 200;
    private MapView mapView;

    public MapFragment() {
        // Required empty public constructor
    }

    public static MapFragment newInstance() {
        MapFragment fragment = new MapFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {

        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_map, container, false);
        mapView = rootView.findViewById(R.id.baidu_map_view);

        LatLng centerPoint = new LatLng(22.255925,113.541112);//中心点经纬度，坐标倒过来

        MapStatus.Builder builder = new MapStatus.Builder();
        builder.zoom(18.0f)//缩放级别为18级，即最大的放大级别
                .target(centerPoint);//设置中心点
        mapView.getMap().setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

        BitmapDescriptor bitmap_school = BitmapDescriptorFactory.fromResource(R.drawable.school);
        BitmapDescriptor bitmap_shop = BitmapDescriptorFactory.fromResource(R.drawable.shop);

        Handler handler=new Handler(Looper.getMainLooper())
        {
            @Override
            public void handleMessage(@NonNull Message msg){
                super.handleMessage(msg);
                if(msg.what==WHAT_DATA_OK){
                    String content=msg.getData().getString("data");
                    if(null!=content){
                        try {
                            JSONObject jsonObject=new JSONObject(content);
                            JSONArray shops=jsonObject.getJSONArray("shops");
                            for(int index=0;index<shops.length();index++){
                                JSONObject shop=shops.getJSONObject(index);

                                LatLng centerPoint = new LatLng(shop.getDouble("latitude"),shop.getDouble("longitude"));//中心点经纬度
                                MarkerOptions markerOption=null;
                                if(index==0){
                                    markerOption = new MarkerOptions().icon(bitmap_school).position(centerPoint);
                                }
                                else{
                                    markerOption = new MarkerOptions().icon(bitmap_shop).position(centerPoint);
                                }
                                Marker marker = (Marker) mapView.getMap().addOverlay(markerOption);
                                OverlayOptions textOption = new TextOptions().bgColor(0xff008080).fontSize(50)
                                        .fontColor(0xff000000).text(shop.getString("name")).rotate(0).position(centerPoint);
                                mapView.getMap().addOverlay(textOption);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        };

        mapView.getMap().setOnMarkerClickListener(maker -> {
            Toast.makeText(getContext(), "Marker被点击了！", Toast.LENGTH_SHORT).show();
            return false;
        });

        Runnable runnable=new Runnable(){
            @Override
            public void run() {
                try {
                    URL url=new URL("http://file.nidama.net/class/mobile_develop/data/bookstore.json");
                    HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
                    httpURLConnection.setUseCaches(false);//禁用缓存
                    httpURLConnection.connect();//建立tcp连接，但不获取数据
                    if(httpURLConnection.getResponseCode()==HttpURLConnection.HTTP_OK)
                    {
                        InputStream inputStream=httpURLConnection.getInputStream();
                        InputStreamReader inputStreamReader=new InputStreamReader(inputStream);
                        BufferedReader bufferedReader=new BufferedReader(inputStreamReader);

                        String line="";
                        StringBuffer stringBuffer=new StringBuffer();
                        while(null!=(line=bufferedReader.readLine()))//读一行数据
                        {
                            stringBuffer.append(line);
                        }
                        Message message=new Message();
                        message.what= WHAT_DATA_OK;
                        Bundle bundle=new Bundle();
                        bundle.putString("data",stringBuffer.toString());
                        message.setData(bundle);

                        handler.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        new Thread(runnable).start();

        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行MapView. onResume ()，实现地图生命周期管理
        mapView.onResume();
    }
    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行MapView. onPause ()，实现地图生命周期管理
        mapView.onPause();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行MapView.onDestroy()，实现地图生命周期管理
        mapView.onDestroy();
    }
}